import { Effect, Reducer } from 'umi';

import {
  subscribeWidget,
  canelSubscribeWidget,
  getWidgetParams,
  getLevels,
  getWidgetData,
} from '@/services/selfquery';
import { buildFilterConfigs, threeSearchFilter, configFilter } from '@/pages/SelfQuery/utils';
import { DATA_ACTION_TYPE } from '@/pages/SelfQuery/constants';

import {
  IChartConfig,
  IChartDataFilterConfigs,
  IFilter,
  ICostCenter,
  IDepartment,
  ISubject,
} from '../type';

export interface WidgetModelState {
  indexDetail: any;
  originalFilterConfigs: any;
  filterConfigs: any;
  formFilters: Array<any>;
  viewId: any;
  widget: any;
  costCenters: Array<ICostCenter>;
  departments: Array<IDepartment>;
  subjects: Array<ISubject>;
  formFiltersDrills: Array<any>;
  drillList: Array<any>;
  drillSelectsArr: any;
}

export interface WidgetModelType {
  namespace: 'widget';
  state: WidgetModelState;
  effects: {
    fetchIndexDetail: Effect;
    subscribeWidget: Effect;
    canelSubscribeWidget: Effect;
    fetchWidget: Effect;
    fetchData: Effect;
    fetchDrillSelectsArr: Effect;
    clearCondition: Effect;
  };
  reducers: {
    save: Reducer;
  };
}

const WidgetModel: WidgetModelType = {
  namespace: 'widget',

  state: {
    indexDetail: {}, // 显示的指标详情数据集合
    originalFilterConfigs: {}, // 原始的封装过滤数据的条件
    filterConfigs: {}, // 封装过滤数据的条件（用于下钻）
    formFilters: [], // 当前图表表单中的过滤筛选条件
    viewId: null, // 图表的ID
    widget: {}, // 图表配置
    costCenters: [], // 成本中心数据
    departments: [], // 部门数据
    subjects: [], // 支出科目数据
    formFiltersDrills: [], // 当前图表表单中的下钻过滤条件
    drillList: [], // 下钻列表
    drillSelectsArr: [], // 下钻选中的值
  },

  effects: {
    // 获取显示的指标详情
    *fetchIndexDetail({ payload }: any, { put }: any) {
      yield put({
        type: 'save',
        payload: { indexDetail: payload },
      });

      // 假如是清除，同步清除下钻路径和筛选条件
      if (JSON.stringify(payload) === '{}') {
        yield put({
          type: 'save',
          payload: { drillList: [] },
        });
        yield put({
          type: 'save',
          payload: { formFilters: [] },
        });
        yield put({
          type: 'save',
          payload: { formFiltersDrills: [] },
        });
      }
    },

    // 清除下钻路径和筛选条件
    *clearCondition({}: any, { put }: any) {
      yield put({
        type: 'save',
        payload: { drillList: [] },
      });
      yield put({
        type: 'save',
        payload: { formFilters: [] },
      });
      yield put({
        type: 'save',
        payload: { formFiltersDrills: [] },
      });
    },

    // 获取下钻选中的值
    *fetchDrillSelectsArr({ payload }: any, { put }: any) {
      yield put({
        type: 'save',
        payload: { drillSelectsArr: payload },
      });
    },

    // 获得操作的指标 筛选条件
    *fetchWidget({ payload }: any, { call, put }: any) {
      const widget = yield call(getWidgetParams, payload);
      const { threeSearchVals } = payload;
      const config: IChartConfig = JSON.parse(widget.payload.config);
      widget.payload.config = config;
      let originalFilterConfigs: IChartDataFilterConfigs = buildFilterConfigs(config);
      let formFilters: Array<IFilter> = [];
      //三段式搜索
      let filterConfigs: IChartDataFilterConfigs = threeSearchFilter(
        config,
        threeSearchVals,
        formFilters,
      );
      filterConfigs = configFilter(filterConfigs);
      const viewId = widget.payload.viewId;
      const levels = yield call(getLevels);
      // 原始的封装过滤数据的条件
      yield put({
        type: 'save',
        payload: { originalFilterConfigs },
      });
      // 封装过滤数据的条件（用于下钻）
      yield put({
        type: 'save',
        payload: { filterConfigs },
      });
      // 当前图表表单中的过滤筛选条件
      yield put({
        type: 'save',
        payload: { formFilters },
      });
      // 图表的ID
      yield put({
        type: 'save',
        payload: { viewId },
      });
      // 图表配置
      yield put({
        type: 'save',
        payload: { widget: widget.payload },
      });
      // 成本中心数据
      yield put({
        type: 'save',
        payload: { costCenters: levels.payload.costCenters },
      });
      // 部门数据
      yield put({
        type: 'save',
        payload: { departments: levels.payload.departments },
      });
      // 支出科目数据
      yield put({
        type: 'save',
        payload: { subjects: levels.payload.subjects },
      });
    },

    // 过滤重新获取数据
    *fetchData({ payload, callback }: any, { select, call, put }: any) {
      const {
        viewId,
        //原始的封装过滤数据的条件
        originalFilterConfigs,
        //图表表单中的过滤筛选条件
        formFilters,
        //当前图表表单中的下钻过滤条件
        formFiltersDrills,
        //当前图表表单中的过滤筛选条件
        filterConfigs,
        // 目前展示的图表数据集合
        indexDetail,
      } = yield select((state: any) => state.widget);
      let originalFilterConfigsNew: IChartDataFilterConfigs = { ...originalFilterConfigs };
      let { type, pararms, drillList } = payload;
      if (type) {
        let { groups, filters } = pararms;
        //筛选
        if (type == DATA_ACTION_TYPE.filter) {
          //保存当前图表表单中的过滤筛选条件(为了在下钻时，能加回去）
          yield put({
            type: 'save',
            payload: { formFilters: filters },
          });
          //筛选没有groups，所有需要赋值当前下钻的groups
          groups = filterConfigs.groups;
          filters = originalFilterConfigs.filters //原始的过滤值
            .concat(formFiltersDrills ? formFiltersDrills : []) //加上下钻的筛选值
            .concat(filters); //加上当前图表表单中的过滤筛选
        }

        if (type == DATA_ACTION_TYPE.drills) {
          //保存当前下钻的历史路径
          yield put({
            type: 'save',
            payload: { drillList: drillList || [] },
          });
          //保存当前图表表单中的下钻过滤条件（为了在自定义筛选时，能加回去）
          yield put({
            type: 'save',
            payload: { formFiltersDrills: filters },
          });
          //原本自带的groups加上新的下钻的groups
          groups = originalFilterConfigs.groups.concat(groups);
          filters = originalFilterConfigs.filters //原始的过滤值
            .concat(formFilters ? formFilters : []) //加上表单自定义的筛选值
            .concat(filters); //加上当前图表表单中的下钻过滤条件

            

        }
        originalFilterConfigsNew = {
          ...originalFilterConfigsNew,
          ...{ groups, filters },
        };

      } else {
        originalFilterConfigsNew = { ...originalFilterConfigsNew, ...payload };

      }
      //加工
      originalFilterConfigsNew = configFilter(originalFilterConfigsNew);
      // 重新获取图表数据
      const dataRecord = yield call(getWidgetData, {
        id: viewId,
        body: JSON.stringify(originalFilterConfigsNew),
      });

      // 回调方法提示是否过滤成功
      if (callback) callback(dataRecord);

      if (dataRecord) {
        const newIndexDetail = JSON.parse(JSON.stringify(indexDetail));
        // 同步更新详情数据集合
        newIndexDetail.dataRecord = dataRecord.payload;
        newIndexDetail.filterConfigs = originalFilterConfigsNew;
        // 更新展示的图表详情数据
        yield put({
          type: 'save',
          payload: { indexDetail: newIndexDetail },
        });
        // 更新下钻数据
        yield put({
          type: 'save',
          payload: { filterConfigs: originalFilterConfigsNew },
        });
      }
    },

    // 订阅指标
    *subscribeWidget({ payload, callback }, { call }) {
      const response = yield call(subscribeWidget, JSON.stringify(payload));

      if (callback) callback(response);
    },

    // 取消订阅指标
    *canelSubscribeWidget({ payload, callback }, { call }) {
      const response = yield call(canelSubscribeWidget, JSON.stringify(payload));

      if (callback) callback(response);
    },
  },

  reducers: {
    save(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};

export default WidgetModel;
